var mysql = require("mysql");
// 引入Node.js的内置模块
const readline = require("readline");

// 创建readline接口实例
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
// 监听输入流结束事件
rl.on("close", () => {
//   console.log("标准输入流已经关闭");
});

function read(msg) {
  return new Promise((resolve, reject) => {
    rl.question(msg + ": ", (answer) => {
      resolve(answer);
    });
  });
}
function testConnect(config) {
  try {
    var connection = mysql.createConnection(config);
    connection.connect();
    connection.query(
      "SELECT 1 + 1 AS solution",
      function (error, results, fields) {
        if (error) throw error;
        console.log(results[0].solution == 2 ? "恭喜，连接成功 ✓" : "连接失败");
      }
    );
    connection.end();
  } catch (e) {
    console.log("连接失败");
    console.log(e);
  }
}
async function main() {
  console.log("mysql测试程序已启动");
  let host = await read("请输入ip");
  let port = await read("请输入port");
  let user = await read("请输入user");
  let password = await read("请输入password");
  let database = await read("请输入database");
  let config = {
    host,
    port,
    user,
    password,
    database,
  };
  rl.close();
  console.log("您输入的配置如下：");
  console.log(config);
  console.log("开始测试连接...");
  testConnect(config);
}
main();
